package com.xiaoyu.client.ui.activity.main.mine.my_info;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Log;
import android.util.TimeUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.techfansy.bottomDialog.BottomDialog;
import com.techfansy.moreImageSelected.BitmapUtils;
import com.techfansy.photo.PhotoSelect;
import com.techfansy.utils.PermissionUtils;
import com.xiaoyu.client.R;
import com.xiaoyu.client.model.mine.MineBean;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.dialog.ModificationInfoDialog;
import com.xiaoyu.commonlib.BillionCardConstants;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.base.BaseActivityWithTitle;
import com.xiaoyu.commonlib.utils.CCircleImageView;
import com.xiaoyu.commonlib.utils.CheckFormatUtils;
import com.xiaoyu.commonlib.utils.PreferencesUtil;
import com.xiaoyu.commonlib.utils.YMDTimeShow;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static java.lang.System.currentTimeMillis;

/**
 * @author jx
 * @date 创建时间 2018/10/15
 * @Description 修改昵称
 */
public class ModifiedDataActivity extends BaseActivityWithTitle {

    public static final int ADDRESS = 0;
    @BindView(R.id.activity_modified_gender)
    TextView mGender;
    @BindView(R.id.activity_modified_birth)
    TextView mBirth;
    @BindView(R.id.activity_modified_head_portrait)
    CCircleImageView mHead;
    @BindView(R.id.onlynumber)
    TextView mOnlyNumber;//亿友号
    @BindView(R.id.individuation)
    EditText mIndividuation;
    @BindView(R.id.nickname)
    EditText mNickName;
    @BindView(R.id.address)
    TextView mAddress;
    @BindView(R.id.reciver_tel)
    TextView mReciverTel;
    @BindView(R.id.hint_txt)
    TextView mHintTxt;
    private TextView mRightText;
    private String mTitleImg;
    private String path;


    @Override
    protected void loadContentView(ViewGroup parent) {
        setTitleText("修改资料");
        View mView = LayoutInflater.from(this).inflate(R.layout.activity_modified_data, parent, true);
        ButterKnife.bind(this);
        initView();
        getMineInfo();//获取个人信息
    }

    private void initView() {
        mNickName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mNickName.setCursorVisible(true);
            }
        });
        addRightTxt();
    }

    //添加右侧按钮
    private void addRightTxt() {
        mRightText = new TextView(this);
        mRightText.setText("保存");
        mRightText.setTextSize(17);
        mRightText.setTextColor(getResources().getColor(R.color.color_blue_27));
        mRightText.setOnClickListener(this);
        addRightView(mRightText, 0);
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        setDialog();
    }

    //弹窗
    private void setDialog() {
        final ModificationInfoDialog dialog = new ModificationInfoDialog(this);
        dialog.setIModifcationInfo(new ModificationInfoDialog.IModificationInfoListener() {
            @Override
            public void OnModificationPhone() {
                modificationInfo();
                dialog.dismiss();
            }
        });
        dialog.setIModifcationInfoDismiss(new ModificationInfoDialog.IModificationInfoListenerDismiss() {
            @Override
            public void OnModificationDismiss() {
                dialog.dismiss();
                finish();
            }
        });
        dialog.show();
    }

    @OnClick(R.id.activity_modified_gender_relative)
    public void genderClick() {
        new BottomDialog(this).addItemSheet(R.string.man, new BottomDialog.SheetListener() {
            @Override
            public void setOnSheet(int i) {
                mGender.setText(R.string.man);
            }
        }).addItemSheet(R.string.woman, new BottomDialog.SheetListener() {
            @Override
            public void setOnSheet(int i) {
                mGender.setText(R.string.woman);
            }
        }).setCancel(new BottomDialog.SheetListener() {
            @Override
            public void setOnSheet(int i) {
            }
        }).show();
    }

    @OnClick(R.id.activity_modified_birth_relative)
    public void birthClick() {
        YMDTimeShow.setTimePop(this, mBirth);
    }

    @OnClick(R.id.activity_modified_img_relative)
    public void headPortraitClick() {
        setPopupPhoto();
    }

    //选择相册
    private void setPopupPhoto() {
        new BottomDialog(this).addItemSheet(R.string.photo_album_to_choose, new BottomDialog.SheetListener() {
            @Override
            public void setOnSheet(int i) {
                permissionUtils.setPermissionUtils(ModifiedDataActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PhotoSelect.REQUEST_CAMERA, new PermissionUtils.RequestPermissionListener() {
                    @Override
                    public void permission(int i) {
                        new PhotoSelect(ModifiedDataActivity.this, true, true);
                    }
                });

            }
        }).addItemSheet(R.string.photo, new BottomDialog.SheetListener() {
            @Override
            public void setOnSheet(int i) {
                permissionUtils.setPermissionUtils(ModifiedDataActivity.this, new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA
                }, PhotoSelect.REQUEST_CAMERA, new PermissionUtils.RequestPermissionListener() {
                    @Override
                    public void permission(int i) {
                        new PhotoSelect(ModifiedDataActivity.this, false, true);
                    }
                });

            }
        }).setCancel(new BottomDialog.SheetListener() {
            @Override
            public void setOnSheet(int i) {
            }
        }).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //接收“相册与拍照”获取到的图片
        if (resultCode == PhotoSelect.REQUEST_CAMERA) {
            if (data == null) return;
            try {
                path = data.getExtras().getString("path");
                Bitmap bitmap = BitmapUtils.getBitmap(path, 800, 800);
                mHead.setImageBitmap(bitmap);
                uploadOSSUrl(path, currentTimeMillis() + path.substring(path.lastIndexOf("/") + 1));//将图片上传至OSS
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //获取选中默认地址
        if (requestCode == ADDRESS && resultCode == AddressActivity.RESULT_OK && data != null) {
            mReciverTel.setText(data.getStringExtra(AddressActivity.ADDRESS_TEL));
            mAddress.setText(data.getStringExtra(AddressActivity.ADDRESS_DETAILS));
            if (mAddress.equals("")) {
                mHintTxt.setVisibility(View.VISIBLE);
            } else {
                mHintTxt.setVisibility(View.GONE);
            }
        }
    }

    @OnClick(R.id.activity_modified_data_address)
    public void addressClick() {
        Intent intent = new Intent(this, AddressActivity.class);
        startActivityForResult(intent, ADDRESS);
    }


    private void getMineInfo() {
        showLoading();
        NetworkManager.getMineInfo(new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                dissmissLoading();
                succeedResultInfo(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
                dissmissLoading();
            }
        });
    }

    private void succeedResultInfo(String result) {
        if (result.length() == 0 || result == null) {
            return;
        }
        MineBean bean = new Gson().fromJson(result, MineBean.class);
        Glide.with(this).load(bean.getData().getUserphoto()).into(mHead);
        PreferencesUtil.commit(PreferencesUtil.TITLE_HEAD, bean.getData().getUserphoto());
        mOnlyNumber.setText(bean.getData().getOnlynumber());
        if (bean.getData().getAddress().equals("")) {
            mHintTxt.setVisibility(View.VISIBLE);
        } else {
            mHintTxt.setVisibility(View.GONE);
        }
        mIndividuation.setText(bean.getData().getIndividuation());
        mNickName.setText(bean.getData().getNickname());
        mGender.setText(bean.getData().getSex());
        mBirth.setText(bean.getData().getDateofbirth());
        mAddress.setText(bean.getData().getAddress());
        mReciverTel.setText(bean.getData().getReceiver() + "    " + bean.getData().getTel());
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == mRightText) {
            modificationInfo();
        }
    }

    private void uploadOSSUrl(String filePath, String objectKey) {
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(BillionCardConstants.BACKET_NAME, objectKey, filePath);
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(BillionCardConstants.ACCESS_KEY_ID, BillionCardConstants.ACCESS_KEY_SECRET);
        try {
            OSSClient oss = new OSSClient(this, BillionCardConstants.ENDPOINT, credentialProvider);
            PutObjectResult putResult = oss.putObject(put);
            mTitleImg = "https://yikabangb.oss-cn-beijing.aliyuncs.com/" + objectKey;
            PreferencesUtil.commit(PreferencesUtil.TITLE_HEAD, mTitleImg);
        } catch (ClientException e) {
            // 本地异常如网络异常等
            e.printStackTrace();
        } catch (ServiceException e) {
            // 服务异常
        }
    }

    //修改个人信息
    private void modificationInfo() {
        NetworkManager.modificationInfo(mNickName.getText().toString(), mIndividuation.getText().toString(),
                mBirth.getText().toString(), PreferencesUtil.getString(PreferencesUtil.TITLE_HEAD, ""), mGender.getText().toString(), new CommonHttpResponser() {
                    @Override
                    public void onSuccess(String result) {
                        finish();
                        PreferencesUtil.commit(PreferencesUtil.TITLE_HEAD, mTitleImg);
                    }

                    @Override
                    public void onFailed(String errorCode, String errorDiscription) {
                    }
                });
    }
}